package view.conponent;

import com.alibaba.fastjson.JSON;
import model.hospital.Patient;
import model.user.Staff;
import net.ToServer;
import net.passClass.PassData;
import net.passClass.PassPatient;
import viewModel.CurrentUser;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatientManager extends Box {
    final int WIDTH = 1080;

    private JTable table;
    private Vector<String> titles;
    private Vector<Vector<String>> tableData;
    private DefaultTableModel tableModel;

    public PatientManager() {
        //指定垂直布局
        super(BoxLayout.Y_AXIS);



        //组装表格
        String[] ts = {"姓名","性别","生日","身份证号","电话","紧急联系人","紧急联系人电话","UID","医生UID","床位UID"};
        titles = new Vector<>();
        titles.addAll(Arrays.asList(ts));

        tableData = new Vector<>();

        tableModel = new DefaultTableModel(tableData, titles);
        table = new JTable(tableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane);

        JPanel textFieldPanel = new JPanel();
        textFieldPanel.setMaximumSize(new Dimension(WIDTH, 80));
        textFieldPanel.setMinimumSize(new Dimension(870, 80));
        textFieldPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        Box box1 = Box.createVerticalBox();
        JTextField name = new JTextField(9);
        JLabel nameStr = new  JLabel("姓名");
        box1.add(nameStr);
        box1.add(name);


        Box box2 = Box.createVerticalBox();
        JTextField sex = new JTextField(9);
        JLabel sexStr = new  JLabel("性别");
        box2.add(sexStr);
        box2.add(sex);


        Box box3 = Box.createVerticalBox();
        JTextField birthday = new JTextField(9);
        JLabel birthdayStr = new  JLabel("生日");
        box3.add(birthdayStr);
        box3.add(birthday);

        Box box4 = Box.createVerticalBox();
        JTextField idNumber = new JTextField(9);
        JLabel idNumberStr = new  JLabel("身份证号");
        box4.add(idNumberStr);
        box4.add(idNumber);


        Box box5 = Box.createVerticalBox();
        JTextField tel = new JTextField(9);
        JLabel telStr = new  JLabel("电话");
        box5.add(telStr);
        box5.add(tel);


        Box box6 = Box.createVerticalBox();
        JTextField emergencyContact = new JTextField(9);
        JLabel emergencyContactStr = new  JLabel("紧急联系人");
        box6.add(emergencyContactStr);
        box6.add(emergencyContact);


        Box box7 = Box.createVerticalBox();
        JTextField emergencyTel = new JTextField(9);
        JLabel emergencyTelStr = new  JLabel("紧急联系人电话");
        box7.add(emergencyTelStr);
        box7.add(emergencyTel);


        textFieldPanel.add(box1);
        textFieldPanel.add(box2);
        textFieldPanel.add(box3);
        textFieldPanel.add(box4);
        textFieldPanel.add(box5);
        textFieldPanel.add(box6);
        textFieldPanel.add(box7);
        this.add(textFieldPanel);

        JPanel btnPanel = new JPanel();
        btnPanel.setMaximumSize(new Dimension(WIDTH, 80));
        btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        JButton addBtn = new JButton("添加");
        JButton deleteBtn = new JButton("删除");
        JButton updateBtn = new JButton("修改");
        JButton getBtn = new JButton("查找");
        JButton refreshBtn = new JButton("刷新");

        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
                long time = 0;
                try {
                    String str = birthday.getText();
                    String pattern = "^\\d{4}-\\d{1,2}-\\d{1,2}";

                    Pattern r = Pattern.compile(pattern);
                    Matcher m = r.matcher(str);
                    if (m.matches()) {
                        time = dateFormat.parse(str).getTime();
                    }
                } catch (ParseException parseException) {
                    JOptionPane.showMessageDialog(textFieldPanel, "信息格式错误");
                }
                PassData receive = ToServer.receive("/patient/add","name:"+name.getText()+"\n" +
                        "sex:" +sex.getText()+"\n" +
                        "birthday:" +time+"\n" +
                        "idNumber:" +idNumber.getText()+"\n" +
                        "tel:" +tel.getText()+"\n" +
                        "emergencyContact:" +emergencyContact.getText()+"\n" +
                        "doctorUID:" + ((Staff)CurrentUser.user).getUid()+"\n" +
                        "emergencyTel:" +emergencyTel.getText());
                requestData();
            }
        });

        deleteBtn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                int[] selected = table.getSelectedRows();
                for (int num: selected) {
                    System.out.println(num);
                    ToServer.receive("/patient/delete","uid:"+table.getValueAt(num,7));
                }
                requestData();
            }
        });

        updateBtn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
                long time = 0;
                try {
                    String str = birthday.getText();
                    String pattern = "^\\d{4}-\\d{1,2}-\\d{1,2}";

                    Pattern r = Pattern.compile(pattern);
                    Matcher m = r.matcher(str);
                    if (m.matches()) {
                        time = dateFormat.parse(str).getTime();
                    }
                } catch (ParseException parseException) {
                    JOptionPane.showMessageDialog(textFieldPanel, "信息格式错误");
                }

                int selected = table.getSelectedRow();
                ToServer.receive("/patient/update",
                        "name:"+name.getText()+"\n" +
                                "uid:"+table.getValueAt(selected,7)+"\n" +
                                "sex:" +sex.getText()+"\n" +
                                "birthday:" +time+"\n" +
                                "idNumber:" +idNumber.getText()+"\n" +
                                "tel:" +tel.getText()+"\n" +
                                "emergencyContact:" +emergencyContact.getText()+"\n" +
                                "emergencyTel:" +emergencyTel.getText());
                requestData();
            }
        });

        getBtn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
                long time = 0;
                try {
                    String str = birthday.getText();
                    String pattern = "^\\d{4}-\\d{1,2}-\\d{1,2}";

                    Pattern r = Pattern.compile(pattern);
                    Matcher m = r.matcher(str);
                    if (m.matches()) {
                        time = dateFormat.parse(birthday.getText()).getTime();
                    }
                } catch (ParseException parseException) {
                    JOptionPane.showMessageDialog(textFieldPanel, "信息格式错误");
                }
                PassPatient receive =(PassPatient) ToServer.receive("/patient/get",
                        "name:"+name.getText()+"\n" +
                                "sex:" +sex.getText()+"\n" +
                                "birthday:" +time+"\n" +
                                "idNumber:" +idNumber.getText()+"\n" +
                                "tel:" +tel.getText()+"\n" +
                                "emergencyContact:" +emergencyContact.getText()+"\n" +
                                "emergencyTel:" +emergencyTel.getText());
                requestData(receive.getData());
            }
        });

        table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){

            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = table.getSelectedRow();
                if(row != -1) {
                    name.setText(table.getValueAt(table.getSelectedRow(),0).toString());
                    sex.setText(table.getValueAt(table.getSelectedRow(),1).toString());
                    birthday.setText(String.valueOf(table.getValueAt(table.getSelectedRow(),2)));
                    idNumber.setText(table.getValueAt(table.getSelectedRow(),3).toString());
                    tel.setText(table.getValueAt(table.getSelectedRow(),4).toString());
                    emergencyContact.setText(table.getValueAt(table.getSelectedRow(),5).toString());
                    emergencyTel.setText(table.getValueAt(table.getSelectedRow(),6).toString());
                }
            }
        });

        refreshBtn.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                requestData();
            }
        });

        btnPanel.add(addBtn);
        btnPanel.add(deleteBtn);
        btnPanel.add(updateBtn);
        btnPanel.add(getBtn);
        btnPanel.add(refreshBtn);
        this.add(btnPanel);

        requestData();

    }

    public void requestData(){
        ArrayList<Patient> data = ((PassPatient)ToServer.receive("/patient/get","\n")).getData();
        requestData(data);
    }

    public void requestData(ArrayList<Patient> data){
        tableData.clear();
        for(int i = 0; i<data.size(); i++){
            Patient patient = JSON.parseObject(JSON.toJSONString(data.get(i)),Patient.class);
            Vector<String> vector = new Vector();
            vector.add(patient.getName());
            vector.add(patient.getSex());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
            vector.add(patient.getBirthday()==null?
                    null:
                    dateFormat.format(patient.getBirthday()));
            vector.add(patient.getIdNumber());
            vector.add(patient.getTel());
            vector.add(patient.getEmergencyContact());
            vector.add(patient.getEmergencyTel());
            vector.add(patient.getUid());
            vector.add(patient.getDoctorUID());
            vector.add(patient.getBedUID());
            tableData.add(vector);
        }
        tableModel.fireTableDataChanged();

    }

}
